import { User } from '@libs /db/Entitys/User.Enitty';
import { Injectable, Type } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { compareSync } from 'bcryptjs';
import { Repository } from 'typeorm';
let entity = User;

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(entity)
    private readonly UserEntity: Repository<User>,
    private readonly jwtService: JwtService,
  ) {}

  async FindAll() {
    return this.UserEntity.find();
  }

  async Register(body: User) {
    const is = await this.UserEntity.findOne({
      where: { username: body.username },
    });
    console.log(Boolean(is));
    if (is) {
      return {
        code: 500,
        message: '用户名已有人使用哦，在看看其他名称吧',
      };
    }
    const data = await this.UserEntity.create(body as any);
    await this.UserEntity.save(data);
    if (!data) {
      return {
        message: '注册失败,请检查',
        code: 500,
      };
    }
    return {
      message: '注册成功',
      code: 200,
      data: data,
    };
  }

  async Login(body: User) {
    const data = await this.UserEntity.find({
      where: {
        username: body.username,
      },
      select: ['createdAt', 'updateAt', 'id', 'username', 'userpass'],
    });
    if (data.length == 0) {
      return {
        code: 500,
        message: '用户名或者密码错误,请检查输入',
      };
    }
    if (!compareSync(body.userpass, data[0].userpass)) {
      return {
        code: 500,
        message: '用户名或者密码错误,请检查输入',
      };
    }
    return {
      token: this.jwtService.sign(String(data[0].id)),
    };
  }
}
